package com.zmj.comon;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.zmj.base.ResultCodeAndMsg;
import com.zmj.exception.CustomException;

/**
 * @Date 2020-04-25 8:39
 * @Description 远程调用客户端
 */
@Service
public class HttpRemoteClient {

    private Logger logger = LoggerFactory.getLogger(HttpRemoteClient.class);

    @Autowired
    private RestTemplate restTemplate;

    public <T> T getForObject(String url, Map<String, ?> uriVariables, TypeReference<T> type) {
        try {
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, null, String.class,
                uriVariables);
            String body = exchange.getBody();
            T t = JSON.parseObject(body, type);
            logger.info("调用url={}", url);
            return t;
        } catch (Exception ex) {
            logger.info("调用url={},出错", url, ex);
            throw new CustomException(new ResultCodeAndMsg("调用出错"));
        }
    }

    public <T> T postForObject(String url, String jsonParam, TypeReference<T> type, String token) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<String>(jsonParam, headers);
            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            String body = exchange.getBody();
            T t = JSON.parseObject(body, type);
            return t;
        } catch (Exception ex) {
            logger.info("调用url={},出错", url, ex);
            throw new CustomException(new ResultCodeAndMsg("调用出错"));
        }
    }

}
